package com.spi.soconversion.jmsqueue;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.spi.soconversion.base.SOCException;
import com.spi.soconversion.util.ErrorConstants;
import com.spi.soconversion.util.ErrorMessageReader;
import com.spi.soconversion.util.SOCConstants;
import com.spi.soconversion.util.SOCFileWriter;
import com.spi.soconversion.util.SOCUtility;

public class JMSQueueProcessor {
	
	private String dirName;
	private List<String> files= new ArrayList<String>();
	private String d_logFileName;
	private SOCFileWriter d_fileWriter;	
	private JMSQueue jmsClient;
	private List<String> messageList = new ArrayList<String>();
	
	public JMSQueueProcessor(JMSQueue jmsClient,String dir,String logFileName, SOCFileWriter fileWriter)
	{
		this.dirName = dir;
		d_logFileName = logFileName;
		d_fileWriter = fileWriter;
		this.jmsClient=jmsClient;
	}
	
	public String getDirName()
	{
		return this.dirName;
	}
	
	public Boolean pushToQueue() 
	{
		boolean result = false;
		
		try {
			getFiles();
			processFile();
			sendToQueue();
			result=true;		
		} catch (SOCException e) {
			result = false;
		}
		
		return result;
	}
	
	private void getFiles() throws SOCException
	{
		File XMLDirRef= new File(dirName);
		if (!XMLDirRef.exists())
		{
			d_fileWriter.write(d_logFileName, SOCUtility.writeLogMessage(ErrorMessageReader.getError(
					ErrorConstants.INVALID_OUTPUT_DIRECTORY)+dirName));
			throw new SOCException(
					ErrorMessageReader.getError(
							ErrorConstants.INVALID_OUTPUT_DIRECTORY)+dirName);
		}
	
		File[] subDir=XMLDirRef.listFiles();
		
		if(subDir!=null)
		{
			for(File file : subDir)
			{
				if(file.isFile())				{
					String absolutePath = file.getAbsolutePath();					
					files.add(absolutePath);
				}
			}
		}
	}
		
	private void processFile() throws SOCException
	{
		if(files!=null && files.size()>0)
		{
			for(String file:files)
			{
				JMSFileReader fileReader = new JMSFileReader(file,d_logFileName,d_fileWriter);
				String fileContent = fileReader.fileReader();
				messageList.add(fileContent);
			}
		}
		else
		{
			d_fileWriter.write(d_logFileName, SOCUtility.writeLogMessage(SOCConstants.NO_XMLS_FOR_JMS_QUEUE_UNDER_DIR+dirName));
		}
		
	}
	
	private void sendToQueue() throws SOCException
	{
		if(messageList!=null && messageList.size()>0){
			jmsClient.pushToQueue(messageList);
		}
	}
}
